/*NOTICE

This software was produced for the U. S. Government
under Contract No. FA8721-09-C-0002, and is
subject to the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation Clause
(DFARS) 252.227-7014 (JUN 1995)

(c) 2009 The MITRE Corporation. All Rights Reserved.
*/
package org.mitre.xmltransform;
import java.io.*;
import org.mitre.xmltransform.transform.Transform;
import org.mitre.xmltransform.transform.TransformFactory;

public class XmlTransformer {	
	/**
	 * @param args
	 */
	
	private static String USAGE = "Usage: XmlTransformer < input file > < transform > < output file > < transform specific inputs >";
	
	public static void main(String[] args) {
		if (args.length < 3) {
			System.out.println(USAGE);
			System.exit(0);
		}
		File inputFile = new File(args[0]);
		if (!inputFile.exists()) {
			System.err.println("Input file '" + args[0] + "' does not exist.");
			System.exit(-1);
		}
		if (!inputFile.canRead()) {
			System.err.println("Input file '" + args[0] + "' can not be read.");
			System.exit(-1);
		}
		String transform = args[1];
		File outputFile = new File(args[2]);
		if (outputFile.exists() && !outputFile.canWrite()) {
			System.err.println("Can not write to file '" + args[2] + "'");
			System.exit(-1);
		}
		
		String[] txArgs = null;
		if (args.length > 3) {
			// we have transform specific inputs
			txArgs = new String[args.length - 3];
			for (int i = 3; i < args.length; i++) {
				txArgs[i-3] = args[i];
			}
		}
		XmlTransformer transformer = new XmlTransformer();
		int errorCode = transformer.initialize(inputFile, transform, outputFile, txArgs);
		if (errorCode != Transform.SETARGS_NO_ERROR) {
			if (errorCode == Transform.SETARGS_BAD_ARGUMENT_COUNT) {
				System.out.println(transformer.getTransformUsageMessage());
				System.exit(0);				
			} else {
				System.out.println(transformer.getSetArgumentsErrorMessage());
				System.exit(0);
			}
		}
		
		transformer.transform();
	}
	
	public XmlTransformer() {
	}
	
	public int initialize(File pInputFile, String pTransform, File pOutputFile, String[] pTransformArguments) {
		mTransform = TransformFactory.getInstance().getTransform(pTransform);
		mTransform.initialize(pInputFile, pOutputFile);
		return mTransform.setArguments(pTransformArguments);
	}
	
	private String getTransformUsageMessage() {
		return mTransform.getUsageMessage();
	}
	
	private String getSetArgumentsErrorMessage() {
		return mTransform.getSetArgumentErrorMessage();
	}
	
	public void transform() {
		mTransform.transform();
	}
			
	private Transform mTransform;
}
